<template>
  <div>
    <el-form ref="form" label-width="80px" :data="spu">
      <el-form-item label="SPU名称">
        <el-input placeholder="SPU名称" v-model="spu.spuName"></el-input>
      </el-form-item>
      <el-form-item label="品牌">
        <el-select placeholder="请选择品牌" v-model="spu.tmId">
          <el-option
            :value="tm.id"
            :label="tm.tmName"
            v-for="(tm, index) in tradeMarkList"
            :key="tm.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述">
        <el-input
          v-model="spu.description"
          type="textarea"
          rows="4"
          placeholder="描述"
        ></el-input>
      </el-form-item>
      <el-form-item label="SPU图片">
        <el-upload
          action="dev-api/admin/product/fileUpload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :on-success="handleSuccess"
          :file-list="spuImageList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性">
        <el-select
          v-model="attrIdAndAttrName"
          :placeholder="`还有${unSelectedSaleAttr.length}项未选择`"
        >
          <el-option
            :value="unSelected.id + ':' + unSelected.name"
            :label="unSelected.name"
            v-for="(unSelected, index) in unSelectedSaleAttr"
            :key="unSelected.id"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrIdAndAttrName"
          @click="addSaleAttr"
          >添加销售属性</el-button
        >
        <el-table style="width: 100%" border :data="spu.spuSaleAttrList">
          <el-table-column
            type="index"
            label="序号"
            width="80px"
            align="center"
          >
          </el-table-column>
          <el-table-column prop="saleAttrName" label="属性值" width="width">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称列表" width="width">
            <template slot-scope="{ row, $index }">
              <el-tag
                :key="tag.id"
                v-for="(tag, index) in row.spuSaleAttrValueList"
                closable
                :disable-transitions="false"
                @close="handleClose(row, index)"
              >
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                class="input-new-tag"
                v-if="row.inputVisible"
                v-model="row.inputValue"
                ref="saveTagInput"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              >
              </el-input>
              <el-button
                v-else
                class="button-new-tag"
                size="small"
                @click="showInput(row)"
                >添加</el-button
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="width">
            <template slot-scope="{ row, $index }">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="spu.spuSaleAttrList.splice($index, 1)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSpu">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "SpuForm",
  data() {
    return {
      dialogImageUrl: "",
      dialogVisible: false,
      // SPU信息
      spu: {
        category3Id: 0,
        description: "",
        spuName: "",
        tmId: "",
        spuImageList: [],
        spuSaleAttrList: [],
      },
      spuImageList: [], // spu图片
      tradeMarkList: [], // 品牌信息
      saleAttrList: [], // 平台销售属性(一共3个)
      attrIdAndAttrName: "", // 收集未选择的销售属性的id
    };
  },
  computed: {
    // 计算出未选择的销售属性
    unSelectedSaleAttr() {
      return this.saleAttrList.filter(
        (v) =>
          !this.spu.spuSaleAttrList.some((item) => item.saleAttrName === v.name)
      );
    },
  },
  methods: {
    // 照片墙删除的回调
    handleRemove(file, fileList) {
      this.spuImageList = fileList;
    },
    // 照片墙预览的回调
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 照片墙上传成功的回调
    handleSuccess(res, file, fileList) {
      this.spuImageList = fileList;
    },
    // 发请求获取数据(点击修改)
    async initSpuData(spu) {
      // 获取spu信息
      let spuResult = await this.$API.spu.reqSpu(spu.id);
      if (spuResult.code === 200) {
        this.spu = spuResult.data;
      }

      // 获取品牌信息
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code === 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }

      // 获取spu图片
      let spuImageResult = await this.$API.spu.reqSpuImageList(spu.id);
      if (spuImageResult.code === 200) {
        spuImageResult.data.forEach((v) => {
          v.url = v.imgUrl;
          v.name = v.imgName;
        });
        this.spuImageList = spuImageResult.data;
      }

      // 获取平台销售属性
      let saleResult = await this.$API.spu.reqBaseSaleAttrList();
      if (saleResult.code === 200) {
        this.saleAttrList = saleResult.data;
      }
    },
    // 发请求获取数据(点击添加)
    async addSpuData(category3Id) {
      this.spu.category3Id = category3Id;

      // 获取品牌信息
      let tradeMarkResult = await this.$API.spu.reqTradeMarkList();
      if (tradeMarkResult.code === 200) {
        this.tradeMarkList = tradeMarkResult.data;
      }

      // 获取平台销售属性
      let saleResult = await this.$API.spu.reqBaseSaleAttrList();
      if (saleResult.code === 200) {
        this.saleAttrList = saleResult.data;
      }
    },
    // 添加销售属性
    addSaleAttr() {
      const [baseSaleAttrId, saleAttrName] = this.attrIdAndAttrName.split(":");
      this.attrIdAndAttrName = "";
      this.spu.spuSaleAttrList.push({
        baseSaleAttrId,
        saleAttrName,
        spuSaleAttrValueList: [],
      });
    },
    // 点击添加属性值名称,展示输入框
    showInput(row) {
      this.$set(row, "inputVisible", true);
      this.$set(row, "inputValue", "");
      this.$nextTick(() => {
        this.$refs.saveTagInput.focus();
      });
    },
    // 添加属性值名称的输入框失去焦点
    handleInputConfirm(row) {
      row.inputVisible = false;
      let { baseSaleAttrId, inputValue } = row;
      inputValue = inputValue.trim();
      // inputValue不能为空
      if (inputValue) {
        // inputValue不能和其他属性值重复
        let result = row.spuSaleAttrValueList.some(
          (v) => v.saleAttrValueName === inputValue
        );
        if (result) {
          this.$message("属性值名称不能重复!");
          row.inputValue = "";
          return;
        }
        row.spuSaleAttrValueList.push({
          baseSaleAttrId,
          saleAttrValueName: inputValue,
        });
      }
      row.inputValue = "";
    },
    // 删除属性值名称
    handleClose(row, index) {
      row.spuSaleAttrValueList.splice(index, 1);
    },
    // 点击保存
    async addOrUpdateSpu() {
      this.spu.spuImageList = this.spuImageList.map((v) => {
        return {
          imageName: v.name,
          imageUrl: (v.response && v.response.data) || v.url,
        };
      });
      let result = await this.$API.spu.reqAddOrUpdateSpu(this.spu);
      if (result.code === 200) {
        this.$message.success("保存成功");
        this.$emit("changeScene", { scene: 0, flag: this.spu.id });
        Object.assign(this._data, this.$options.data()); // 清除数据
      }
    },
    // 点击取消
    cancel() {
      this.$emit("changeScene", { scene: 0, flag: this.spu.id });
      Object.assign(this._data, this.$options.data()); // 清除数据
    },
  },
};
</script>

<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
